from rest_framework.views import APIView
from .utils import get_alipay
from orders.models import OrderInfo
from rest_framework import serializers
from django.conf import settings
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from .models import Payment


class AliPaymentView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, order_id):
        # 查询订单
        try:
            order = OrderInfo.objects.get(pk=order_id)
        except:
            raise serializers.ValidationError("订单不存在")
        alipay = get_alipay()
        order_string = alipay.api_alipay_trade_page_pay(
            # 订单编号
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城支付-" + order_id,
            return_url=settings.RETURN_URL
        )
        # 拼接返回给客户端的支付宝支付的url
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        return Response({'alipay_url': alipay_url})


class AliPaymentVarifyView(APIView):
    def put(self, request):
        alipay = get_alipay()
        # 获取支付宝返回的参数 并转成字典
        # data = request.data
        data = request.query_params.dict()
        signature = data.pop('sign')
        # 订单编号
        order_id = data["out_trade_no"]
        # 支付宝交易编号
        trade_id = data["trade_no"]
        # 如果支付成功 则保存订单编号 支付编号
        success = alipay.verify(data, signature)
        if success:
            Payment.objects.create(order_id=order_id, trade_id=trade_id)
            return Response({"trade_id": trade_id})
        else:
            raise serializers.ValidationError("支付失败")
